﻿using HZYProject.Core.Repositories;
using HZYProject.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;

namespace HZYProject.Service
{
    public class ModuleService : IModuleService
    {
        private readonly IRepository<Module, Guid> _moduleRepository;
        private readonly IRepository<ModuleCategory, int> _mcRepository;
        public ModuleService(IRepository<Module, Guid> moduleRepository,
             IRepository<ModuleCategory, int> mcRepository
            )
        {
            _moduleRepository = moduleRepository;
            _mcRepository = mcRepository;

        }

        
        public List<ModuleCategory> GetModuleCategories() {
            return _mcRepository.GetAll().Include("Modules").ToList();
        }

        public async Task<PagedResultDto<Module>> GetPaginatedResult(GetModuleInput input)
        {
            var query = _moduleRepository.GetAll();

            //搜索
            if (!string.IsNullOrEmpty(input.Name))
            {
                query = query.Where(x => x.Name.Contains(input.Name));
            }
             

            //统计查询数据的总条数，用于分页计算总页数
            var count = query.Count();
            //根据需求进行排序，然后进行分页逻辑的计算
            query = query.OrderByDescending(x => x.ModuleID).Skip((input.CurrentPage - 1) * input.MaxResultCount).Take(input.MaxResultCount);
            //将查询结果转换为List集合，加载到内存中
            var models = await query.AsNoTracking().ToListAsync();


            var dtos = new PagedResultDto<Module>
            {
                TotalCount = count,
                CurrentPage = input.CurrentPage,
                MaxResultCount = input.MaxResultCount,
                Data = models,
                FilterText = input.FilterText,
            };
            return dtos;
        }
    }
}
